﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Collections.Generic;

public partial class admin_product : System.Web.UI.Page
{
    DAOProduct dao_product = new DAOProduct();
    DAOCategory dao_category = new DAOCategory();
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadData();
        }
    }

    private void LoadData()
    {
        gvProduct.DataSource = dao_product.GetAllProduct();
        gvProduct.DataBind();

        ddlCategory.DataSource = dao_category.GetAllCategory();
        ddlCategory.DataTextField = "CateName";
        ddlCategory.DataValueField = "CateId";
        ddlCategory.DataBind();
    }

    protected void gvProduct_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvProduct.PageIndex = e.NewPageIndex;
        gvProduct.EditIndex = -1;
        LoadData();
    }
    protected void gvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Label lblId = (Label)gvProduct.Rows[e.RowIndex].FindControl("lblProId");
        int ProId = Convert.ToInt16(lblId.Text);
        Product p = new Product();
        p.ProId = ProId;
        int kq = dao_product.DeleteProduct(p);
        if (kq > 0)
        {
            LoadData();
        }
    }
    protected void txtAddProduct_Click(object sender, EventArgs e)
    {
        String fileName = null;
        if (UploadFile.HasFile)
        {
            fileName = Path.GetFileName(UploadFile.PostedFile.FileName);
            UploadFile.PostedFile.SaveAs(Server.MapPath("~/images/") + fileName);
        }
        Category c = new Category { CateID = Convert.ToInt32(ddlCategory.SelectedValue) };
        
        Product product = new Product
        {
            Category = c,
            ProName = txtProName.Text,
            Image = fileName,
            Price = Convert.ToDouble(txtprice.Text),
            Quantity = Convert.ToInt32(txtQuantityAdd.Text),
            IsSale = chbxIsSale.Checked,
            StartingDate = DateTime.Now,
            Content = txtContent.Text
        };

        int kq = dao_product.InsertProduct(product);
        if (kq>0)
        {
            Response.Redirect("product.aspx");
        }

    }

    protected void Button1_Click(object sender, EventArgs e)//btnseach
    {
        String key = txtSearchProduct.Text;
        
        gvProduct.DataSource = dao_product.SeachProduct(key);
        gvProduct.DataBind();

    }
}